﻿using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
namespace LTP.Common
{
    /// <summary> 
    /// 类   名：JSONConvert 
    /// 描   述：JSON解析类 
    /// 编   写：dnawo 
    /// 站   点：http://www.mzwu.com/ 
    /// 日   期：2010-01-06 
    /// 版   本：1.1.0 
    /// </summary> 
    /// 
    public static class JSONConvert
    {
        #region 全局变量

        private static JSONObject _json = new JSONObject();//寄存器 
        private static readonly string _SEMICOLON = "@semicolon";//分号转义符 
        private static readonly string _COMMA = "@comma"; //逗号转义符 

        #endregion

        #region 字符串转义
        /// <summary> 
        /// 字符串转义,将双引号内的:和,分别转成_SEMICOLON和_COMMA 
        /// </summary> 
        /// <param name="text"></param> 
        /// <returns></returns> 
        private static string StrEncode(string text)
        {
            MatchCollection matches = Regex.Matches(text, "\\\"[^\\\"] \\\"");
            foreach (Match match in matches)
            {
                text = text.Replace(match.Value, match.Value.Replace(":", _SEMICOLON).Replace(",", _COMMA));
            }

            return text;
        }

        /// <summary> 
        /// 字符串转义,将_SEMICOLON和_COMMA分别转成:和, 
        /// </summary> 
        /// <param name="text"></param> 
        /// <returns></returns> 
        private static string StrDecode(string text)
        {
            return text.Replace(_SEMICOLON, ":").Replace(_COMMA, ",");
        }

        #endregion

        #region JSON最小单元解析

        /// <summary> 
        /// 最小对象转为JSONObject 
        /// </summary> 
        /// <param name="text"></param> 
        /// <returns></returns> 
        private static JSONObject DeserializeSingletonObject(string text)
        {
            JSONObject jsonObject = new JSONObject();

            MatchCollection matches = Regex.Matches(text, "(\\\"(?<key>[^\\\"] )\\\":\\\"(?<value>[^,\\\"] )\\\")|(\\\"(?<key>[^\\\"] )\\\":(?<value>[^,\\\"\\}] ))");
            foreach (Match match in matches)
            {
                string value = match.Groups["value"].Value;
                jsonObject.Add(match.Groups["key"].Value, _json.ContainsKey(value) ? _json[value] : StrDecode(value));
            }

            return jsonObject;
        }

        /// <summary> 
        /// 最小数组转为JSONArray 
        /// </summary> 
        /// <param name="text"></param> 
        /// <returns></returns> 
        private static JSONArray DeserializeSingletonArray(string text)
        {
            JSONArray jsonArray = new JSONArray();

            MatchCollection matches = Regex.Matches(text, "(\\\"(?<value>[^,\\\"] )\")|(?<value>[^,\\[\\]] )");
            foreach (Match match in matches)
            {
                string value = match.Groups["value"].Value;
                jsonArray.Add(_json.ContainsKey(value) ? _json[value] : StrDecode(value));
            }

            return jsonArray;
        }

        /// <summary> 
        /// 反序列化 
        /// </summary> 
        /// <param name="text"></param> 
        /// <returns></returns> 
        private static string Deserialize(string text) 
     {
         text = StrEncode(text);//转义;和,    

         int count = 0;
         string key = string.Empty;
         string pattern = "(//{[^//[//]//{//}]+//})|(//[[^//[//]//{//}]+//])";

         while (Regex.IsMatch(text, pattern))
         {
             MatchCollection matches = Regex.Matches(text, pattern);
             foreach (Match match in matches)
             {
                 key = "___key" + count + "___";

                 if (match.Value.Substring(0, 1) == "{")
                     _json.Add(key, DeserializeSingletonObject(match.Value));
                 else
                     _json.Add(key, DeserializeSingletonArray(match.Value));

                 text = text.Replace(match.Value, key);

                 count++;
             }
         }
         return text;  

     }

        #endregion

        #region 公共接口

        /// <summary> 
        /// 序列化JSONObject对象 
        /// </summary> 
        /// <param name="text"></param> 
        /// <returns></returns> 
        public static JSONObject DeserializeObject(string text)
        {
            return _json[Deserialize(text)] as JSONObject;
        }

        /// <summary> 
        /// 序列化JSONArray对象 
        /// </summary> 
        /// <param name="text"></param> 
        /// <returns></returns> 
        public static JSONArray DeserializeArray(string text)
        {
            return _json[Deserialize(text)] as JSONArray;
        }

        /// <summary> 
        /// 反序列化JSONObject对象 
        /// </summary> 
        /// <param name="jsonObject"></param> 
        /// <returns></returns> 
        public static string SerializeObject(JSONObject jsonObject)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("{");
            foreach (KeyValuePair<string, object> kvp in jsonObject)
            {
                if (kvp.Value is JSONObject)
                {
                    sb.Append(string.Format("\"{0}\":{1},", kvp.Key, SerializeObject((JSONObject)kvp.Value)));
                }
                else if (kvp.Value is JSONArray)
                {
                    sb.Append(string.Format("\"{0}\":{1},", kvp.Key, SerializeArray((JSONArray)kvp.Value)));
                }
                else if (kvp.Value is System.String)
                {
                    sb.Append(string.Format("\"{0}\":\"{1}\",", kvp.Key, kvp.Value));
                }
                else
                {
                    sb.Append(string.Format("\"{0}\":\"{1}\",", kvp.Key, ""));
                }
            }
            if (sb.Length > 1)
                sb.Remove(sb.Length - 1, 1);
            sb.Append("}");
            return sb.ToString();
        }

        /// <summary> 
        /// 反序列化JSONArray对象 
        /// </summary> 
        /// <param name="jsonArray"></param> 
        /// <returns></returns> 
        public static string SerializeArray(JSONArray jsonArray)
        {
            StringBuilder sb = new StringBuilder();  
            sb.Append("[");  
            for (int i = 0; i < jsonArray.Count; i++)  
            {  
                if (jsonArray[i] is JSONObject)  
                {  
                    sb.Append(string.Format("{0},", SerializeObject((JSONObject)jsonArray[i])));  
                }  
                else if (jsonArray[i] is JSONArray)  
                {  
                    sb.Append(string.Format("{0},", SerializeArray((JSONArray)jsonArray[i])));  
                }  
                else if (jsonArray[i] is String)  
                {
                    sb.Append(string.Format("\"{0}\",", jsonArray[i])); 


                }  
                else  
                {
                    sb.Append(string.Format("\"{0}\",", "")); 


                }  
  
            }  
            if (sb.Length > 1)  
                sb.Remove(sb.Length - 1, 1);  
            sb.Append("]");  
            return sb.ToString();  
        }  
        #endregion   

        /// <summary>
        /// 将JSON格式字符串反序列化为Status集合对象
        /// </summary>
        /// <param name="url">同ReadJsonDataToString()</param>
        /// <param name="httpRequestMethod">HTTP请求方式</param>
        /// <returns></returns>
        public static List<Status> DeserializeJsonToListObject(string text)
        {
            try
            {
                List<Status> listObj;
                MemoryStream stream = new MemoryStream();
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List<Status>));
                StreamWriter wr = new StreamWriter(stream);
                wr.Write(text);
                wr.Flush();
                stream.Position = 0;
                Object obj = ser.ReadObject(stream);
                listObj = (List<Status>)obj;
                wr.Close();
                stream.Close();
                return listObj;
            }
            catch (Exception e)
            {
                string a = e.Message;
                return null;
            }
        }
        /// <summary>
        /// 将JSON格式字符串反序列化为id集合对象
        /// </summary>
        /// <param name="url">同ReadJsonDataToString()</param>
        /// <param name="httpRequestMethod">HTTP请求方式</param>
        /// <returns></returns>
        public static List<Queryid> DeserializeJsonToListSinaId(string text)
        {
            try
            {
                List<Queryid> listObj;
                MemoryStream stream = new MemoryStream();
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List<Queryid>));
                StreamWriter wr = new StreamWriter(stream);
                wr.Write(text);
                wr.Flush();
                stream.Position = 0;
                Object obj = ser.ReadObject(stream);
                listObj = (List<Queryid>)obj;
                wr.Close();
                stream.Close();
                return listObj;
            }
            catch (Exception e)
            {
                string a = e.Message;
                return null;
            }
        }
        /// <summary>
        /// 将json转换成status
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static Status DeserializeToStatus(string json)
        {
            Status obj = Activator.CreateInstance<Status>();
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
            {
                System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
                return (Status)serializer.ReadObject(ms);
            }
        }
 

        /// <summary>
        /// 将JSON格式字符串反序列化为Comment集合对象
        /// </summary>
        /// <param name="url">同ReadJsonDataToString()</param>
        /// <param name="httpRequestMethod">HTTP请求方式</param>
        /// <returns></returns>
        public static List<Comment> DeserializeJsonToListObjectComment(string text)
        {
            try
            {
                List<Comment> listObj;
                MemoryStream stream = new MemoryStream();
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List<Comment>));
                StreamWriter wr = new StreamWriter(stream);
                wr.Write(text);
                wr.Flush();
                stream.Position = 0;
                Object obj = ser.ReadObject(stream);
                listObj = (List<Comment>)obj;
                wr.Close();
                stream.Close();
                return listObj;
            }
            catch (Exception e)
            {
                return null;
            }
        }
        /// <summary>
        /// 将JSON格式字符串反序列化为Status集合对象
        /// </summary>
        /// <param name="text">同ReadJsonDataToString()</param>
        /// <returns></returns>
        public static List<Status> DeserializeJsonToListObjectStatus(string text)
        {
            try
            {
                List<Status> listObj;
                MemoryStream stream = new MemoryStream();
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List<Status>));
                StreamWriter wr = new StreamWriter(stream);
                wr.Write(text);
                wr.Flush();
                stream.Position = 0;
                Object obj = ser.ReadObject(stream);
                listObj = (List<Status>)obj;
                wr.Close();
                stream.Close();
                return listObj;
            }
            catch (Exception e)
            {
                return null;
            }
        }
        public static List<StatusCount> DeserializeJsonToListObjectStatusCount(string text)
        {
            try
            {
                List<StatusCount> listObj;
                MemoryStream stream = new MemoryStream();
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List<StatusCount>));
                StreamWriter wr = new StreamWriter(stream);
                wr.Write(text);
                wr.Flush();
                stream.Position = 0;
                Object obj = ser.ReadObject(stream);
                listObj = (List<StatusCount>)obj;
                wr.Close();
                stream.Close();
                return listObj;
            }
            catch (Exception e)
            {
                return null;
            }
        }


    }

    /// <summary> 
    /// 类   名：JSONObject 
    /// 描   述：JSON对象类 
    /// 版   本：1.1.0 
    /// 更新历史： 
    ///      2010-01-06   继承Dictionary<TKey, TValue>代替this[] 
    /// </summary> 
    public class JSONObject : Dictionary<string, object>
    { }

    /// <summary> 
    /// 类   名：JSONArray 
    /// 描   述：JSON数组类 
    /// 版   本：1.1.0 
    /// 更新历史： 
    ///      2010-01-06   继承List<T>代替this[] 
    /// </summary> 
    public class JSONArray : List<object>
    { }
    /// <summary>
    /// 一条微博的转发数和评论数
    /// </summary>
    public class StatusCount
    {
        public string id { get; set; }
        public string rt { get; set; }
        public string comments { get; set; }
    }

   /// <summary>
   /// 我的微博
   /// </summary>
    public class Status
    {
       
        public string created_at { get; set; }

        public string id { get; set; }

        public string text { get; set; }

        public string source { get; set; }
        
        public bool favorited { get; set; }
       
        public bool truncated { get; set; }

        //public string geo { get; set; }

        public string in_reply_to_status_id { get; set; }

        public string in_reply_to_user_id { get; set; }

        public string in_reply_to_screen_name { get; set; }

        public string thumbnail_pic { get; set; }

        public string bmiddle_pic { get; set; }

        public string original_pic { get; set; }

        public User user { get; set; }

        public RetweetedStatus retweeted_status { get; set; }
    }
    /// <summary>
    /// 评论Comment
    /// </summary>
    public class Comment 
    {
        public long id {  set;  get;}
        /// <summary>
        /// 评论内容
        /// </summary>
        public string text  {  set; get;}
        /// <summary>
        /// 评论来源
        /// </summary>
        public string source  { set; get;}
        /// <summary>
        /// 是否收藏
        /// </summary>
        public bool favorited  {  set;  get;  }
        /// <summary>
        /// 是否被截断 
        /// </summary>
        public bool truncated { set;get; }
        /// <summary>
        /// 评论时间
        /// </summary>
        public string created_at { set;get; }
        /// <summary>
        /// 会员ID
        /// </summary>
        public User user { set; get; }
        /// <summary>
        /// 微博ID
        /// </summary>
        public Status status { set; get; }
        /// <summary>
        /// 评论来源
        /// </summary>
        public Reply_comment reply_comment { set; get; }
    
    }
    /// <summary>
    /// 回复评论
    /// 结构同 comment
    /// </summary>
    public class Reply_comment
    {
        public long id { set; get; }
        /// <summary>
        /// 评论内容
        /// </summary>
        public string text { set; get; }
        /// <summary>
        /// 评论来源
        /// </summary>
        public string source { set; get; }
        /// <summary>
        /// 是否收藏
        /// </summary>
        public bool favorited { set; get; }
        /// <summary>
        /// 是否被截断 
        /// </summary>
        public bool truncated { set; get; }
        /// <summary>
        /// 评论时间
        /// </summary>
        public string created_at { set; get; }
        /// <summary>
        /// 会员ID
        /// </summary>
        public Reply_user user { set; get; }
        /// <summary>
        /// 微博ID
        /// </summary>
        public Status status_id { set; get; }
        /// <summary>
        /// 评论来源
        /// </summary>
        public Reply_comment reply_comment { set; get; }

    }
    /// <summary>
    /// 评论中的User
    /// </summary>
    public class User
    {

        public string id { get; set; }

        public string screen_name { get; set; }

        public string name { get; set; }

        public string province { get; set; }

        public string city { get; set; }

        public string location { get; set; }

        public string description { get; set; }

        public string url { get; set; }

        public string profile_image_url { get; set; }

        public string domain { get; set; }

        public string gender { get; set; }

        public string followers_count { get; set; }

        public string friends_count { get; set; }

        public string statuses_count { get; set; }

        public string favourites_count { get; set; }

        public string created_at { get; set; }

        public string following { get; set; }

        public string verified { get; set; }

        public string allow_all_act_msg { get; set; }

        public string geo_enabled { get; set; }
        public Status Status { get; set; }

    }
    /// <summary>
    /// 回复评论中的user
    /// Reply_user
    /// </summary>
    public class Reply_user
    {

        public string id { get; set; }

        public string screen_name { get; set; }

        public string name { get; set; }

        public string province { get; set; }

        public string city { get; set; }

        public string location { get; set; }

        public string description { get; set; }

        public string url { get; set; }

        public string profile_image_url { get; set; }

        public string domain { get; set; }

        public string gender { get; set; }

        public string followers_count { get; set; }

        public string friends_count { get; set; }

        public string statuses_count { get; set; }

        public string favourites_count { get; set; }

        public string created_at { get; set; }

        public string following { get; set; }

        public string verified { get; set; }

        public string allow_all_act_msg { get; set; }

        public string geo_enabled { get; set; }
        public Status Status { get; set; }

    }
    public class PostUser
    {
        
        public string id { get; set; }
        
        public string screen_name { get; set; }
        
        public string name { get; set; }
        
        public string province { get; set; }
        
        public string city { get; set; }
        
        public string location { get; set; }
        
        public string description { get; set; }
        
        public string url { get; set; }
        
        public string profile_image_url { get; set; }
        
        public string domain { get; set; }
        
        public string gender { get; set; }
        
        public string followers_count { get; set; }
        
        public string friends_count { get; set; }
        
        public string statuses_count { get; set; }
        
        public string favourites_count { get; set; }
        
        public string created_at { get; set; }
        
        public string following { get; set; }
        
        public string verified { get; set; }
        
        public string allow_all_act_msg { get; set; }
        
        public string geo_enabled { get; set; }
        public Status Status { get; set; }

    }
    /// <summary>
    /// 转发的微博
    /// </summary>
    public class RetweetedStatus
    {
        
        public string created_at { get; set; }
        
        public string id { get; set; }
        
        public string text { get; set; }
        
        public string source { get; set; }
        
        public string favorited { get; set; }
        
        public string truncated { get; set; }
        
        //public string geo { get; set; }
        
        public string in_reply_to_status_id { get; set; }
        
        public string in_reply_to_user_id { get; set; }
        
        public string in_reply_to_screen_name { get; set; }
        
        public string thumbnail_pic { get; set; }
        
        public string bmiddle_pic { get; set; }
        
        public string original_pic { get; set; }
        
        public PostUser user { get; set; }

        public RetweetedStatus retweeted_status { get; set; }
    }
    public class Queryid 
    {
        public string id { get; set; }
    }

   
}
//嗯，json写完了，下面来看下使用的方法：


////序列化 
//JSONArray jsonArray = new JSONArray(); 
//jsonArray.Add("2006"); 
//jsonArray.Add("2007"); 
//jsonArray.Add("2008"); 
//jsonArray.Add("2009"); 
//jsonArray.Add("2010"); 

//JSONObject jsonObject = new JSONObject(); 
//jsonObject.Add("domain", "mzwu.com"); 
//jsonObject.Add("years", jsonArray); 

//Console.WriteLine(JSONConvert.SerializeObject(jsonObject)); 

////反序列化   "{\"domain\":\"mzwu.com\",\"years\":[2006,2007,2008,2009,2010]}" 
//JSONObject json = JSONConvert.DeserializeObject(JSONConvert.SerializeObject(jsonObject)); 
//if (json != null) 
//{ 
//     Console.WriteLine(json["domain"]); 
//     Console.WriteLine(((JSONArray)json["years"])[3]); 
//} 

